import { loginApi } from '@/api/user'

import { useRouter } from 'vue-router'
const route = useRouter()
const state = () => ({
  token: '', // 登录token
  info: {},  // 用户信息,
  menuTitle:'',
  conversationList: [],
  chatInfo:null,
  chatIndex: -1, 
  messageList: [],
  isCompleted: false,
  addMsgList:[],
  isImLogin:false,
  toUserId:'',
  userInfo:{},//聊天对象
})

// getters
const getters = {
  token(state) {
    return state.token
  },

}

// mutations
const mutations = {
  tokenChange(state, token) {
    state.token = token
    localStorage.setItem('token', token)
  },
  infoChange(state, info) {
    state.info = info
  },
  changeMenuTitle(state,value){
    state.menuTitle   = value
  },
  setConversationList(state, list) {
    state.conversationList = list
  },
  chatInfoChange (state,info){
    state.chatInfo = info
  },
  changeChatIndex(state, index) {
    state.chatIndex = index
  },
  setMsg(state, obj) {
    state.messageList = obj.messageList
    state.isCompleted = obj.isCompleted
  },
  setAddMsgList(state, list) {
    state.addMsgList = list
  },
  imLogimChange(state,flag){
    state.isImLogin = flag
  },
  readList(state, list) {
    if (state.messageList[0].conversationID == list[0].conversationID) {
      state.messageList.map(item => {
        item.isPeerRead = true
      })
    }
  },
  setToUserId(state,id){
    state.toUserId = id
  }
  ,
  toUserInfo(state,data){
    state.userInfo = data
  }, 
   pushMsg(state, obj) {
    if (obj.isSend) {
      state.messageList = [...state.messageList, ...obj.messageList]
    } else {
      state.messageList = [...obj.messageList, ...state.messageList]
      state.isCompleted = obj.isCompleted
    }


  },
 
}

// actions
const actions = {
  // login by login.vue
  login({ commit, dispatch }, params) {
    return new Promise((resolve, reject) => {
      loginApi(params)
        .then(res => {
          commit('tokenChange', res.data.token)
          localStorage.setItem('info', JSON.stringify(res.data))
          resolve(res.data)
        }).catch(err => {
          reject(err)
        })
    })
  },


  // login out the system after user click the loginOut button
  loginOut({ commit }) {
    localStorage.removeItem('tabs')
    localStorage.removeItem('vuex')
    sessionStorage.removeItem('vuex')
    location.reload()
  }
}

export default {
  namespaced: true,
  state,
  actions,
  getters,
  mutations
}
